package internal

import (
	"github.com/gin-contrib/gzip"
	"github.com/gin-gonic/gin"
	"go-cloud-disk/global"
	"go-cloud-disk/internal/api"
	"go-cloud-disk/internal/dao"
	"go-cloud-disk/internal/middleware"
	"go-cloud-disk/internal/service/setting"
)

func InitRouter() *gin.Engine {
	r := gin.Default()
	//静态资源
	r.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPaths([]string{"/api/"})))
	r.Use(middleware.FrontendFileHandler())

	r.GET("/manifest.json", Manifest)

	v3 := r.Group("/api/v3")
	v3.Use(middleware.CurrentUser())

	r.GET("/site/ping", api.Ping)
	r.GET("/site/captcha", api.Captcha)                             // 验证码
	r.GET("/site/config", middleware.CSRFInit(), api.GetSiteConfig) // 站点全局配置

	api.InitUserRouter(v3)
	api.InitFileRouter(v3)

	return r
}

func test(c *gin.Context) {
	queryRes := GetSettingByNames("a")
	c.JSON(200, queryRes)
}

func GetSettingByNames(names ...string) []dao.Setting {
	var queryRes []dao.Setting
	global.DB.Where("name IN (?)", names).Find(&queryRes)
	return queryRes
}

func Manifest(c *gin.Context) {
	options := setting.GetSettingByNames(
		"siteName",
		"siteTitle",
		"pwa_small_icon",
		"pwa_medium_icon",
		"pwa_large_icon",
		"pwa_display",
		"pwa_theme_color",
		"pwa_background_color",
	)

	c.JSON(200, map[string]interface{}{
		"short_name": options["siteName"],
		"name":       options["siteTitle"],
		"icons": []map[string]string{
			{
				"src":   options["pwa_small_icon"],
				"sizes": "64x64 32x32 24x24 16x16",
				"type":  "image/x-icon",
			},
			{
				"src":   options["pwa_medium_icon"],
				"type":  "image/png",
				"sizes": "192x192",
			},
			{
				"src":   options["pwa_large_icon"],
				"type":  "image/png",
				"sizes": "512x512",
			},
		},
		"start_url":        ".",
		"display":          options["pwa_display"],
		"theme_color":      options["pwa_theme_color"],
		"background_color": options["pwa_background_color"],
	})
}
